var myApp = angular.module('myApp', [ 'ngGrid', 'ui.select2' ]);
myApp.controller('MyCtrl', function($scope, $http) {
	//global variable
	$scope.selectedRows = [];
	//init page item
	$scope.init = function() {
		$http.post(ctx + '/dict/findGroupByCd').success(function(data) {
			$scope.cdList = data.dt;
		});
		$scope.stList = [{"id":0, "lb":"在用"},{"id":1, "lb":"停用"}];
	};
	$scope.init();
	
	//grid
	$scope.pagingOptions = {
		pageSizes : [ 20, 50, 100 ],
		pageSize : 20,
		currentPage : 1,
		onQueryFlag : false
	};
	$scope.$watch('pagingOptions', function(newVal, oldVal) {
		if (newVal !== oldVal/* && newVal.currentPage !== oldVal.currentPage*/) {
			$scope.query();
		}
	}, true);
	$scope.gridOptions = {
		data : 'dt',
		totalServerItems : 'tt',
		columnDefs : [ {
			field : "id",
			displayName : "ID",
			visible : false
		}, {
			field : "cd",
			displayName : "代码"
		}, {
			field : "lb",
			displayName : "标签"
		}, {
			field : "val",
			displayName : "值"
		}, {
			field : "descr",
			displayName : "描述"
		}, {
			field : "remark",
			displayName : "备注"
		},  {
			field : "sortNb",
			displayName : "排序"
		},{
			field : "st",
			displayName : "状态"
		} ],
		enablePaging : true,
		pagingOptions : $scope.pagingOptions,
		enableCellEdit : true,
		keepLastSelected : false,
		showSelectionCheckbox : true,
		selectedItems : $scope.selectedRows,
		i18n : 'zh-cn', rowHeight : 21, footerRowHeight : 35, //plugins : [ngGridDoubleClick ],
		showFooter : true
	};

	$scope.query = function() {
		closeModal($("#queryFormModal"));
		var requestBody = {
			pageNb : $scope.pagingOptions.currentPage,
			pageSize : $scope.pagingOptions.pageSize,
			ffMap : $scope.queryForm
		};
		setTimeout(function() {
			httpPost($http, {"url":ctx + '/dict/findListBy', "data" : requestBody, "ifBlock" : true}, function(data){
				$scope.tt = data.tt;
				$scope.dt = data.dt;
				$scope.gridOptions.$gridScope.toggleSelectAll(false);
				if(data.dt.length === 0){
					toastWarning("没有找到符合查询条件的记录。");
				};
			}, function(errMsg){
				toastError("查询失败。" + errMsg);
			});
		}, 100);
	};
	//trigger query when currentPage not change
	$scope.onQuery = function(){
		$scope.pagingOptions.onQueryFlag = !$scope.pagingOptions.onQueryFlag;
		$scope.pagingOptions.currentPage = 1;
	};

	$scope.refresh = function(){
		hideShadow();
		$scope.onQuery();	
	};

	//utils
	$scope.onClearSelectedRows = function() {
		$scope.gridOptions.$gridScope.toggleSelectAll(false);
	};
	
	//crud
	$scope.onOpenQueryFormModal = function() {
		hideShadow();
		openModal($("#queryFormModal"));
		if($scope.queryForm.st == undefined){
			$scope.queryForm.st = 0;
		}
	};
	
	$scope.onOpenEditFormModal = function(type, id) {
		if(type == "add"){
			$("#cd1").css("display","block");
			$("#cd2").css("display","none");
			$scope.editForm = {};
			$scope.editForm.st = 0;
		}else if(type == "upd"){
			$("#cd1").css("display","block");
			$("#cd2").css("display","none");
			if($scope.selectedRows.length != 1) { toastWarning("请选择一笔记录进行编辑。"); return; }
			httpGet($http, {"url":ctx + '/dict/id/' + $scope.selectedRows[0]['id'], "ifBlock":true}, function(data){
				$scope.editForm = data.dt;
			}, function(errMsg){
				toastWarning("查询此笔记录失败。");
			});
		}else{
			$("#cd1").css("display","none");
			$("#cd2").css("display","block");
			$scope.editForm = {};
			$scope.editForm.st = 0;
		}
		hideShadow();
		openModal($("#editFormModal"));
	};
	$scope.onSaveEditForm = function(){
		closeModal($("#editFormModal"));
		httpPost($http, {"url":ctx + '/dict/save', "data" : $scope.editForm, "ifBlock" : true}, function(data){
			toastSuccess("保存成功");
			$scope.query();
		}, function(errMsg){
			toastError("保存失败,您输入的信息有误，请检查正确之后再保存。" + errMsg);
		});
	};
	$scope.onOpenDelFormModal = function() {
		hideShadow();
		var selectedRowsLength = $scope.selectedRows.length;
		if(selectedRowsLength < 1) { toastWarning("请至少选择一笔记录进行操作。"); return; }
		dialogConfirm("是否确认停用选择的" + selectedRowsLength + "笔记录？", function(){
			var selectedRowsId = [];
			$.each($scope.selectedRows, function(idx, obj){
				selectedRowsId.push(obj.id);
			});
			
			httpPost($http, {"url":ctx + '/dict/updStByIds', "params":{"ids" : selectedRowsId, "st" : 1}, "ifBlock" : true}, function(data){
				toastSuccess("停用成功");
				$scope.query();
			}, function(errMsg){
				toastError("停用失败。" + errMsg);
			});
		});
	};
	//右键菜单功能
	$('#mainDataBlock').contextMenu('menu', {
	      //菜单项样式
	      itemStyle: {
	        fontFamily : 'verdana',
	        backgroundColor : '#F0F0F0',
	        border: 'none',
	        padding: '4px'
	      },
	      //菜单项鼠标放在上面样式
	      itemHoverStyle: {
	        border: '1px solid #fff'
	      },
	      onShowMenu: function(e, menu) {
	    	if($scope.selectedRows.length === 0){
	          $('#del, #edit', menu).remove();
	        }else if($scope.selectedRows.length > 1){
	        	  if($scope.selectedRows[0]['st'] === 0){
		        	  $('#edit', menu).remove(); 
		          }else{
		        	  $('#edit,#del', menu).remove();
		          }		  
		        }else{
		        	 if($scope.selectedRows[0]['st'] === 1){
		        		 $('#del', menu).remove();
		        	 }
		        }
	        return menu;
	      }
		});
});